﻿using Common.Communal;
using ERP.Domain.System;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Repository.Impl;
using System.Repository.Interface;
using System.Text;
using System.Threading.Tasks;

namespace System.Services.Permissions
{
    /// <summary>
    /// 权限服务
    /// </summary>
    public class PermissionService : IPermissionService
    {
        /// <summary>
        /// 权限仓储
        /// </summary>
        private IPermissionRepository _permissionRepository;

        /// <summary>
        /// 构造函数，注入权限仓储
        /// </summary>
        /// <param name="permissionRepository">权限仓储</param>
        public PermissionService(IPermissionRepository permissionRepository)
        {
            _permissionRepository = permissionRepository;
        }

        /// <summary>
        /// 新增权限
        /// </summary>
        /// <param name="permission">权限实体</param>
        /// <returns>返回结果</returns>
        public async Task<ApiResult<int>> Add(Permission permission)
        {
            var result = new ApiResult<int>();
            try
            {
                if (permission.PermissionNo.Length > 50)
                {
                    result.Error(result.Message = "权限编号长度不能超过50个字符");
                    return result;
                }
                if (permission.PermissionName.Length > 100)
                {
                    result.Error(result.Message = "权限名称长度不能超过100个字符");
                    return result;
                }
                if (permission.PermissionType < 1 || permission.PermissionType > 3)
                {
                    result.Error(result.Message = "权限类型无效（1-菜单，2-按钮，3-接口）");
                    return result;
                }
                if (!string.IsNullOrWhiteSpace(permission.PermissionCode) && permission.PermissionCode.Length > 100)
                {
                    result.Error(result.Message = "权限编码长度不能超过100个字符");
                    return result;
                }
                if (!string.IsNullOrWhiteSpace(permission.RoutePath) && permission.RoutePath.Length > 200)
                {
                    result.Error(result.Message = "路由路径长度不能超过200个字符");
                    return result;
                }
                if (!string.IsNullOrWhiteSpace(permission.ComponentPath) && permission.ComponentPath.Length > 200)
                {
                    result.Error(result.Message = "组件路径长度不能超过200个字符");
                    return result;
                }

                // 检查权限编号是否已存在
                var noList = await _permissionRepository.GetAsync(p => p.PermissionNo == permission.PermissionNo && !p.IsDeleted);
                if (noList.Count() > 0)
                {
                    result.Error(result.Message = "权限编号已存在");
                    return result;
                }

                // 检查权限名称是否已存在
                var nameList = await _permissionRepository.GetAsync(p => p.PermissionName == permission.PermissionName && !p.IsDeleted);
                if (nameList.Count() > 0)
                {
                    result.Error(result.Message = "权限名称已存在");
                    return result;
                }

                // 检查权限编码是否已存在（如果提供）
                if (!string.IsNullOrWhiteSpace(permission.PermissionCode))
                {
                    var codeList = await _permissionRepository.GetAsync(p => p.PermissionCode == permission.PermissionCode && !p.IsDeleted);
                    if (codeList.Count() > 0)
                    {
                        result.Error(result.Message = "权限编码已存在");
                        return result;
                    }
                }

                // 初始化默认值
                permission.PermissionStatus = true;
                permission.IsDeleted = false;
                
                // 获取最大的排序值并自增
                var existingPermissions = await _permissionRepository.GetAsync(p => !p.IsDeleted);
                var maxSortOrder = existingPermissions.Any() ? existingPermissions.Max(p => p.SortOrder) : 0;
                permission.SortOrder = maxSortOrder + 1;

                var res = await _permissionRepository.AddAsync(permission);
                if (res > 0)
                {
                    result.Success(res, result.Message = "权限添加成功");
                }
                else
                {
                    result.Error(result.Message = "权限添加失败");
                }
            }
            catch (Exception ex)
            {
                result.Error(result.Message = $"权限添加异常: {ex.Message}");
            }
            return result;
        }

        /// <summary>
        /// 更新权限
        /// </summary>
        /// <param name="permission">权限实体</param>
        /// <returns>返回结果</returns>
        public async Task<ApiResult<int>> Update(Permission permission)
        {
            var result = new ApiResult<int>();
            try
            {
                if (permission.PermissionNo.Length > 50)
                {
                    result.Error(result.Message = "权限编号长度不能超过50个字符");
                    return result;
                }

                if (permission.PermissionName.Length > 100)
                {
                    result.Error(result.Message = "权限名称长度不能超过100个字符");
                    return result;
                }

                if (!string.IsNullOrWhiteSpace(permission.PermissionCode) && permission.PermissionCode.Length > 100)
                {
                    result.Error(result.Message = "权限编码长度不能超过100个字符");
                    return result;
                }

                if (!string.IsNullOrWhiteSpace(permission.RoutePath) && permission.RoutePath.Length > 200)
                {
                    result.Error(result.Message = "路由路径长度不能超过200个字符");
                    return result;
                }

                if (!string.IsNullOrWhiteSpace(permission.ComponentPath) && permission.ComponentPath.Length > 200)
                {
                    result.Error(result.Message = "组件路径长度不能超过200个字符");
                    return result;
                }
                // 检查权限编号是否被其他记录使用
                var noList = await _permissionRepository.GetAsync(p => p.PermissionNo == permission.PermissionNo && p.Id != permission.Id && !p.IsDeleted);
                if (noList.Count() > 0)
                {
                    result.Error(result.Message = "权限编号已被其他权限使用");
                    return result;
                }

                // 检查权限名称是否被其他记录使用
                var nameList = await _permissionRepository.GetAsync(p => p.PermissionName == permission.PermissionName && p.Id != permission.Id && !p.IsDeleted);
                if (nameList.Count() > 0)
                {
                    result.Error(result.Message = "权限名称已被其他权限使用");
                    return result;
                }

                // 检查权限编码是否被其他记录使用（如果提供）
                if (!string.IsNullOrWhiteSpace(permission.PermissionCode))
                {
                    var codeList = await _permissionRepository.GetAsync(p => p.PermissionCode == permission.PermissionCode && p.Id != permission.Id && !p.IsDeleted);
                    if (codeList.Count() > 0)
                    {
                        result.Error(result.Message = "权限编码已被其他权限使用");
                        return result;
                    }
                }
                var res = await _permissionRepository.Update(permission);
                if (res > 0)
                {
                    result.Success(res, result.Message = "权限更新成功");
                }
                else
                {
                    result.Error(result.Message = "权限更新失败");
                }
            }
            catch (Exception ex)
            {
                result.Error(result.Message = $"权限更新异常: {ex.Message}");
            }
            return result;
        }

        /// <summary>
        /// 删除权限（逻辑删除）
        /// </summary>
        /// <param name="id">权限ID</param>
        /// <returns>返回结果</returns>
        public async Task<ApiResult<int>> Delete(int id)
        {
            var result = new ApiResult<int>();
            try
            {
                var existingPermission = await _permissionRepository.GetModelAsync(id);
                // 检查是否有子权限
                var childPermissions = await _permissionRepository.GetAsync(p => p.ParentId == id && !p.IsDeleted);
                if (childPermissions.Count() > 0)
                {
                    result.Error(result.Message = "存在子权限，无法删除");
                    return result;
                }

                // 执行逻辑删除
                existingPermission.IsDeleted = true;
                var res = await _permissionRepository.Update(existingPermission);
                
                if (res > 0)
                {
                    result.Success(res, result.Message = "权限删除成功");
                }
                else
                {
                    result.Error(result.Message = "权限删除失败");
                }
            }
            catch (Exception ex)
            {
                result.Error(result.Message = $"权限删除异常: {ex.Message}");
            }
            return result;
        }
        /// <summary>
        /// 启用/禁用权限
        /// </summary>
        /// <param name="id">主键</param>
        /// <returns>返回结果</returns>
        public async Task<ApiResult<int>> Enable(int id)
        {
            var result = new ApiResult<int>();
            try
            {
                var per = await _permissionRepository.GetModelAsync(id);
                per.PermissionStatus = !per.PermissionStatus;
                var res = await _permissionRepository.Update(per);
                if (res > 0)
                {
                    string statusText = per.PermissionStatus ? "启用" : "禁用";
                    result.Success(res, result.Message = $"用户{statusText}成功");
                }
                else
                {
                    result.Error(result.Message = "权限状态更新失败");
                }
            }
            catch (Exception ex)
            {
                result.Error(result.Message = $"权限状态更新异常: {ex.Message}");
            }
            return result;
        }
    }
}
